var form, iframeIndex;

$(function () {
    initLayUI(function () {
        initGenderDict();
        initButtons();
    });
});

function initLayUI(cb) {
    layui.use(['form'], function () {
        form = layui.form;

        form.verify({
            userName: function (value) {
                if (value.length < 2 || value.length > 12) {
                    return '用户昵称必须2-12位长度';
                }
            }
        });

        form.on('submit(personForm)', function (data) {
            let user = {
                "userName": data.field.userName,
                "email": data.field.email,
                "phone": data.field.phone,
                "gender": parseInt(data.field.gender)
            };
            ajaxUtil.simplePost(user, "/user/updateBaseInfo", function () {
                $("#cardUserName").text(user.userName);
                $("#cardEmail").text(user.email);
                $("#cardPhone").text(user.phone);
                // 更新SessionStorage中用户信息
                user.token = getTempData('userInfo').token;
                user.avatar = getTempData('userInfo').avatar;
                user.createTime = getTempData('userInfo').createTime;
                putTempData('userInfo', user);
            });
            return false;
        });

        form.render();

        cb();
    });

}

function initGenderDict() {
    ajaxUtil.loadDict("sys_user_gender", function (data) {
        let userInfo = getTempData('userInfo');
        $("#cardUserName").text(userInfo.userName);
        $("#cardEmail").text(userInfo.email);
        $("#cardPhone").text(userInfo.phone);
        $("#cardCreateTime").text(userInfo.createTime);
        $("#userAvatar").attr("src", userInfo.avatar);

        form.val('form', {
            "loginAccount": userInfo.loginAccount,
            "userName": userInfo.userName,
            "email": userInfo.email,
            "phone": userInfo.phone
        });

        data.forEach(function (item) {
            let radioStr = "<input type='radio' name='gender' value='" + item.dictValue + "'";
            if (parseInt(item.dictValue) === userInfo.gender) {
                radioStr += " checked ";
            }
            radioStr += " title='" + item.dictLabel + "'/>";
            $("#genderDiv").append(radioStr);
        });

        form.render();
    });
}

function initButtons() {
    $("#userAvatar").click(function () {
        iframeIndex = layerUtil.iframe({
            title: "更换图片",
            area: ['900px', '500px'],
            content: "view/system/profile.html"
        });
    });
}

function reloadParentAvatar(data) {
    $("#userAvatar").attr("src", data);
    let userInfo = getTempData('userInfo');
    userInfo.avatar = data;
    putTempData('userInfo', userInfo);
}